package org.abc.fund.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.abc.fund.repository.funds.FundTagRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * 在应用首次启动且标签数据为空时执行 tag.sql
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DataSqlInitializer implements CommandLineRunner {

    private final DataSource dataSource;
    private final FundTagRepository fundTagRepository;
    private final ResourceLoader resourceLoader;

    @Value("${app.data.init.enabled:true}")
    private boolean initEnabled;

    @Value("${app.data.init.script:classpath:tag.sql}")
    private String initScriptLocation;

    @Override
    public void run(String... args) {
        if (!initEnabled) {
            log.debug("Data SQL initialization disabled.");
            return;
        }
        if (fundTagRepository.count() > 0) {
            log.debug("Fund tags already exist, skip data.sql initialization.");
            return;
        }
        Resource resource = resourceLoader.getResource(initScriptLocation);
        if (!resource.exists()) {
            log.warn("Initialization script {} not found, skip.", initScriptLocation);
            return;
        }
        try {
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resource);
            populator.execute(dataSource);
            log.info("Executed initialization script {} because fund_tag was empty.", initScriptLocation);
        } catch (Exception ex) {
            log.error("Failed to execute initialization script {}", initScriptLocation, ex);
            throw ex;
        }
    }
}


